use std::sync::Arc;
use chrono::{DateTime, Utc, Duration};
use tokio::time::{interval, Duration as TokioDuration};
use tracing::{info, error, debug};

use crate::storage::{MemoryStorage, PersistentStorage, DataPoint, DeviceStatus, MemoryStorageStats, PersistentStorageStats};
use crate::error::{Result, ModbusCollectorError};

/// 数据存储管理器
#[derive(Debug, Clone)]
pub struct DataStorage {
    memory: Arc<MemoryStorage>,
    persistent: Option<Arc<PersistentStorage>>,
    config: StorageConfig,
}

/// 存储配置
#[derive(Debug, Clone)]
pub struct StorageConfig {
    pub enable_persistent: bool,
    pub db_path: String,
    pub history_retention_days: i64,
    pub cleanup_interval_hours: u64,
    pub auto_store_historical: bool,
}

impl Default for StorageConfig {
    fn default() -> Self {
        Self {
            enable_persistent: true,
            db_path: "data/modbus.db".to_string(),
            history_retention_days: 30,
            cleanup_interval_hours: 24,
            auto_store_historical: true,
        }
    }
}

impl DataStorage {
    pub async fn new() -> Result<Self> {
        Self::with_config(StorageConfig::default()).await
    }
    
    pub async fn with_config(config: StorageConfig) -> Result<Self> {
        let memory = Arc::new(MemoryStorage::new());
        
        let persistent = if config.enable_persistent {
            // 确保数据目录存在
            if let Some(parent) = std::path::Path::new(&config.db_path).parent() {
                std::fs::create_dir_all(parent)
                    .map_err(|e| ModbusCollectorError::Storage(format!("Failed to create data directory: {}", e)))?;
            }
            
            let persistent_storage = PersistentStorage::new(&config.db_path).await?;
            Some(Arc::new(persistent_storage))
        } else {
            None
        };
        
        let storage = Self {
            memory,
            persistent,
            config,
        };
        
        // 启动后台清理任务
        storage.start_cleanup_task().await;
        
        info!("Data storage initialized with persistent: {}", storage.config.enable_persistent);
        Ok(storage)
    }
    
    /// 存储数据点
    pub async fn store_data_point(&self, data_point: &DataPoint) -> Result<()> {
        // 始终存储到内存
        self.memory.store_data_point(data_point).await?;
        
        // 如果启用持久化且点位需要历史存储
        if let Some(persistent) = &self.persistent {
            if self.config.auto_store_historical {
                persistent.store_historical_data(data_point).await?;
            }
        }
        
        Ok(())
    }
    
    /// 批量存储数据点
    pub async fn store_data_points(&self, data_points: &[DataPoint]) -> Result<()> {
        for data_point in data_points {
            self.store_data_point(data_point).await?;
        }
        Ok(())
    }
    
    /// 获取最新数据点
    pub async fn get_latest_data_point(&self, point_id: &str) -> Option<DataPoint> {
        self.memory.get_latest_data_point(point_id)
    }
    
    /// 获取设备的所有最新数据点
    pub async fn get_device_latest_data(&self, device_id: &str) -> Vec<DataPoint> {
        self.memory.get_device_latest_data(device_id)
    }
    
    /// 获取所有最新数据点
    pub async fn get_all_latest_data(&self) -> Vec<DataPoint> {
        self.memory.get_all_latest_data()
    }
    
    /// 获取历史数据
    pub async fn get_history_data(
        &self,
        point_id: &str,
        start_time: Option<DateTime<Utc>>,
        end_time: Option<DateTime<Utc>>,
        limit: Option<usize>,
    ) -> Result<Vec<DataPoint>> {
        // 优先从持久化存储获取
        if let Some(persistent) = &self.persistent {
            persistent.get_historical_data(point_id, start_time, end_time, limit).await
        } else {
            // 回退到内存缓存
            Ok(self.memory.get_history_data(point_id, start_time, end_time, limit).await)
        }
    }
    
    /// 更新设备状态
    pub async fn update_device_status(
        &self,
        device_id: &str,
        online: bool,
        error: Option<String>,
    ) -> Result<()> {
        // 更新内存状态
        self.memory.update_device_status(device_id, online, error.clone()).await;
        
        // 更新持久化状态
        if let Some(persistent) = &self.persistent {
            let status = self.memory.get_device_status(device_id)
                .unwrap_or_else(|| crate::storage::DeviceStatus {
                    device_id: device_id.to_string(),
                    online,
                    last_communication: Some(Utc::now()),
                    error_count: if online { 0 } else { 1 },
                    last_error: error,
                });
            
            persistent.store_device_status(&status).await?;
        }
        
        Ok(())
    }
    
    /// 获取设备状态
    pub async fn get_device_status(&self, device_id: &str) -> Option<DeviceStatus> {
        self.memory.get_device_status(device_id)
    }
    
    /// 获取所有设备状态
    pub async fn get_all_device_status(&self) -> Vec<DeviceStatus> {
        self.memory.get_all_device_status()
    }
    
    /// 存储配置
    pub async fn store_config(&self, key: &str, value: &str) -> Result<()> {
        if let Some(persistent) = &self.persistent {
            persistent.store_config(key, value).await
        } else {
            Err(ModbusCollectorError::Storage("Persistent storage not enabled".to_string()))
        }
    }
    
    /// 获取配置
    pub async fn get_config(&self, key: &str) -> Result<Option<String>> {
        if let Some(persistent) = &self.persistent {
            persistent.get_config(key).await
        } else {
            Ok(None)
        }
    }
    
    /// 获取存储统计信息
    pub async fn get_statistics(&self) -> Result<StorageStatistics> {
        let memory_stats = self.memory.get_statistics().await;
        
        let persistent_stats = if let Some(persistent) = &self.persistent {
            Some(persistent.get_statistics().await?)
        } else {
            None
        };
        
        Ok(StorageStatistics {
            memory: memory_stats,
            persistent: persistent_stats,
        })
    }
    
    /// 手动清理过期数据
    pub async fn cleanup_expired_data(&self) -> Result<CleanupResult> {
        let retention_period = Duration::days(self.config.history_retention_days);
        let mut memory_cleaned = 0;
        let mut persistent_cleaned = 0;
        
        // 清理内存缓存
        self.memory.cleanup_expired_data(retention_period).await?;
        memory_cleaned = 1; // 简化计数
        
        // 清理持久化存储
        if let Some(persistent) = &self.persistent {
            persistent_cleaned = persistent.cleanup_expired_data(retention_period).await?;
        }
        
        info!("Cleanup completed: {} memory entries, {} persistent entries", 
              memory_cleaned, persistent_cleaned);
        
        Ok(CleanupResult {
            memory_entries_cleaned: memory_cleaned,
            persistent_entries_cleaned: persistent_cleaned,
        })
    }
    
    /// 启动后台清理任务
    async fn start_cleanup_task(&self) {
        let storage = self.clone();
        let interval_duration = TokioDuration::from_secs(self.config.cleanup_interval_hours * 3600);
        
        tokio::spawn(async move {
            let mut ticker = interval(interval_duration);
            
            loop {
                ticker.tick().await;
                
                debug!("Starting scheduled data cleanup");
                match storage.cleanup_expired_data().await {
                    Ok(result) => {
                        info!("Scheduled cleanup completed: {:?}", result);
                    },
                    Err(e) => {
                        error!("Scheduled cleanup failed: {}", e);
                    }
                }
            }
        });
        
        info!("Background cleanup task started with interval: {} hours", self.config.cleanup_interval_hours);
    }
    
    /// 压缩数据库
    pub async fn compact_database(&self) -> Result<()> {
        if let Some(persistent) = &self.persistent {
            persistent.compact().await
        } else {
            Err(ModbusCollectorError::Storage("Persistent storage not enabled".to_string()))
        }
    }
    
    /// 关闭存储
    pub async fn close(&self) -> Result<()> {
        info!("Closing data storage");
        
        if let Some(persistent) = &self.persistent {
            persistent.close().await?;
        }
        
        info!("Data storage closed");
        Ok(())
    }
}

/// 存储统计信息
#[derive(Debug, Clone)]
pub struct StorageStatistics {
    pub memory: MemoryStorageStats,
    pub persistent: Option<PersistentStorageStats>,
}

/// 清理结果
#[derive(Debug, Clone)]
pub struct CleanupResult {
    pub memory_entries_cleaned: usize,
    pub persistent_entries_cleaned: usize,
}